<template>
    <div class="bg">
        <el-card class="form-card">
            <template #header>
                <div class="card-header">
                    <span>登录</span>
                </div>
            </template>
            <el-form ref="formRef" :model="form" label-width="50px" :rules="rules">
                <el-form-item label="账号" prop="username">
                    <el-input v-model="form.username" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="form.password" show-password />
                </el-form-item>
                <el-form-item>
                    <el-button @click="handleSubmit(formRef)" type="primary">登录</el-button>
                </el-form-item>
            </el-form>
            <el-row class="row-bg" justify="space-between">
                <el-col :span="6">
                    <el-link href="/#/register" type="info">注册账户</el-link>
                </el-col>
                <el-col :span="6">
                    <el-link type="info">忘记密码？</el-link>
                </el-col>
            </el-row>
        </el-card>
    </div>
</template>
<script setup>
import { reactive, ref } from 'vue';
import axios from 'axios';
import admin from '../api/admin';
import { useRouter } from 'vue-router';
let form = reactive({
    username: '',
    password: '',
});
let formRef = ref();
let router = useRouter();
//表单验证规则
const rules = reactive({
    username: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 3, max: 30, message: '账户长度要求3-30之间', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码!', trigger: 'blur' },
        { pattern: /\d{3,}/, message: '密码长度要求3以上数字', trigger: 'blur' },
    ]
})
function handleSubmit(formEl) {
    formEl.validate(async (valid, fields) => {
        if (valid) {
            //通过校验
            let { status, msg, data } = await admin.login({ ...form })
            if (status) {
                //缓存数据
                sessionStorage.id = data.id;
                sessionStorage.role = data.role;
                sessionStorage.token = data.token;
                ElMessage.success(msg);
                router.push('/article/list')
            } else {
                ElMessage.error(msg);
            }
        }
        else {
            //校验失败
            console.log('失败字段:fields');
        }
    })
}
</script>

<style lang="less" scoped>
.bg {
    position: relative;
    min-height: 100vh;
    background: url(../assets/img/login/bg.jpg) top center;
    background-size: cover;

    .form-card {
        position: absolute;
        top: 50%;
        right: 30px;
        transform: translateY(-50%);
        width: 360px;
    }
}
</style>